package com.hl.controller.dizhi;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.hl.domain.ShoppingAddress;
import com.hl.service.IShoppingAddressService;
import com.hl.service.ILiliShopMemberService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.hl.domain.LiliShopMember;

/**
 * 收货地址Controller
 * 
 * @author ruoyi
 * @date 2025-08-12
 */
@RestController
@RequestMapping("/address")
public class ShoppingAddressController extends BaseController
{
    @Autowired
    private IShoppingAddressService shoppingAddressService;

    @Autowired
    private ILiliShopMemberService liliShopMemberService;

    /**
     * 验证memberId是否有效（在member表中存在）
     * @param memberId 用户ID
     * @return true表示有效，false表示无效
     */
    private boolean isValidMemberId(Integer memberId) {
        if (memberId == null || memberId == 0) {
            return false;
        }
        
        try {
            // 调用memberService来验证用户是否存在
            LiliShopMember member = liliShopMemberService.selectLiliShopMemberByMemberId(memberId.toString());
            boolean isValid = member != null;
            return isValid;
        } catch (Exception e) {
            return false;
        }
    }
    /**
     * 查询会员收货地址列表
     *
     * @return 收货地址集合
     */
    @GetMapping("/list")
    public TableDataInfo list(ShoppingAddress shoppingAddress)
    {
        // 强制要求memberId参数，确保数据安全
        if (shoppingAddress.getMemberId() == null) {
            return new TableDataInfo();
        }

        startPage();
        List<ShoppingAddress> list = shoppingAddressService.selectShoppingAddressList(shoppingAddress);
        return getDataTable(list);
    }
    /**
     * 查询会员收货地址列表
     *
     * @return 收货地址集合
     */
    @GetMapping("/list/{memberId}")
    public TableDataInfo listByMemberId(@PathVariable("memberId") Integer memberId)
    {
        // 验证memberId是否有效
        if (!isValidMemberId(memberId)) {
            return new TableDataInfo();
        }

        startPage();
        List<ShoppingAddress> list = shoppingAddressService.selectShoppingAddressByMemberId(memberId);
        return getDataTable(list);
    }
    /**
     * 导出收货地址列表
     */
    @RequiresPermissions("address:address:export")
    @Log(title = "收货地址", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ShoppingAddress shoppingAddress)
    {
        List<ShoppingAddress> list = shoppingAddressService.selectShoppingAddressList(shoppingAddress);
        ExcelUtil<ShoppingAddress> util = new ExcelUtil<ShoppingAddress>(ShoppingAddress.class);
        util.exportExcel(response, list, "收货地址数据");
    }

    /**
     * 获取收货地址详细信息
     */
    // @RequiresPermissions("address:address:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        ShoppingAddress address = shoppingAddressService.selectShoppingAddressById(id);
        if (address == null) {
            return error("地址不存在");
        }
        
        // 验证权限：只能查看自己的地址
        // 由于SecurityUtils.getUserId()返回0，我们使用地址本身的memberId进行验证
        if (!isValidMemberId(address.getMemberId())) {
            return error("地址数据异常，无法访问");
        }
        
        return success(address);
    }

    /**
     * 新增收货地址
     */
    // @RequiresPermissions("address:address:add")
    @Log(title = "收货地址", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ShoppingAddress shoppingAddress)
    {

        // 验证前端传递的memberId是否有效
        if (!isValidMemberId(shoppingAddress.getMemberId())) {
            return error("用户ID无效");
        }

        return toAjax(shoppingAddressService.insertShoppingAddress(shoppingAddress));
    }

    /**
     * 修改收货地址
     */
    // @RequiresPermissions("address:address:edit")
    @Log(title = "收货地址", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ShoppingAddress shoppingAddress)
    {
        // 验证前端传递的memberId是否有效
        if (!isValidMemberId(shoppingAddress.getMemberId())) {
            return error("用户ID无效");
        }
        
        // 验证权限：只能修改自己的地址
        ShoppingAddress existingAddress = shoppingAddressService.selectShoppingAddressById(shoppingAddress.getId());
        if (existingAddress == null) {
            return error("地址不存在");
        }
        
        // 验证地址所有权：确保修改的地址属于同一个用户
        if (!shoppingAddress.getMemberId().equals(existingAddress.getMemberId())) {
            return error("无权限修改此地址");
        }
        
        return toAjax(shoppingAddressService.updateShoppingAddress(shoppingAddress));
    }

    /**
     * 删除收货地址
     */
    // @RequiresPermissions("address:address:remove")
    @Log(title = "收货地址", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        // 验证权限：只能删除自己的地址
        for (Integer id : ids) {
            ShoppingAddress address = shoppingAddressService.selectShoppingAddressById(id);
            if (address == null) {
                return error("地址不存在");
            }
            
            // 验证地址所有权：确保删除的地址属于当前用户
            // 由于SecurityUtils.getUserId()返回0，我们使用地址本身的memberId进行验证
            if (!isValidMemberId(address.getMemberId())) {
                return error("地址数据异常，无法删除");
            }
            
        }

        return toAjax(shoppingAddressService.deleteShoppingAddressByIds(ids));
    }
}
